package com.etheart.lyric.htmlparser.service.jujing;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.util.RegexUtils;
import com.etheart.model.entity.Album;
import com.etheart.model.entity.Song;

@Service("htmlparse_JujingAlbumParseService")
public class JujingAlbumParseService {
	private static final Log logger = LogFactory
			.getLog(JujingAlbumParseService.class);

	public Album getAlbum(Parser parser, String fileName) {
		//http://www.top100.cn/album/index-skcadgctugr4drcbogy.shtml
		String idStr = RegexUtils.getMatcheGroup(".*index-([^\\.]*)\\.shtml",
				fileName);
		Album album = new Album();
		album.setNetId(idStr);
		return getAlbum(parser, album);
	}

	private Album getAlbum(Parser parser, Album album) {
			// 得到专辑名称
			try {
				String albumName = parseAlbumName(parser);
				//album.setName(albumName);//---------------------------
			} catch (Exception e) {
				logger.debug(album.getNetId()+":专辑名称转化错误");
			}
			
			// 得到专辑介绍
			try {
				String albumIntro = parseAlbumIntro(parser);
				album.setIntro(albumIntro);
			} catch (Exception e) {
				logger.debug(album.getNetId()+":专辑介绍转化错误");
			}
			
			// 得到专辑发行 语种 公司 发行时间 等
			String[] strs=null;
			try {
				strs = parseAlbumLanguage(parser);
				if (strs!=null&&strs.length>=3) {
					album.setLanguage(strs[0]);
					album.setConame(strs[1]);
				}
			} catch (Exception e) {
				logger.debug(album.getNetId()+":语种转化错误");
			}
			
			try {
				album.setPublishtime(com.etheart.framework.core.util.DateUtils.parseTimestamp(strs[2]));
			} catch (Exception e2) {
				logger.debug(album.getNetId()+":发行时间转化错误");
			}
			// 专辑图片
			try{
				String pic = parseAlbumImg(parser);
				//album.setPicUrl(pic);//---------------------------------
			} catch (Exception e2) {
				logger.debug(album.getNetId()+":专辑图片转化错误");
			}
	

		return album;
	}

	private String parseAlbumImg(Parser parser) throws ParserException {
		parser.reset();
		NodeFilter imgFilter = new AndFilter(new TagNameFilter("img"),new HasAttributeFilter("width", "190")); 
		//<img src="http://pic.top100.cn/SpecialImg/33/middle_special_323142.jpg" width="190" height="190" />
		// 得到专辑图片地址
		NodeList nodeList = parser.parse(imgFilter);
		for (int i = 0; i < nodeList.size(); i++) {
			Tag tag = (Tag) nodeList.elementAt(i);
			String src = tag.getAttribute("src");
			if (src.indexOf("http://pic.top100.cn/SpecialImg/") != -1 && src.indexOf("SingerImg/nopic")==-1) {
				return src.replace("http://pic.top100.cn/SpecialImg", "");
			}
		}
		return null;
	}

	private String[] parseAlbumLanguage(Parser parser) throws ParserException {
		parser.reset();
		String[] strs=new String[3];
		//<p class="introspecial">语种：国语</p>
		NodeFilter filter = new AndFilter(new TagNameFilter("p"),new HasAttributeFilter("class","introspecial")) ;
		NodeList nodeList = parser.parse(filter);
		Node languageNode  =  nodeList.elementAt(1);
		strs[0] = languageNode.toPlainTextString().replace("语种：", "");
		
		
		//  <p style="padding-left:10px;">唱片公司：金牌大风</p>
        //<p style="padding-left:10px;">发行日期：2010-06-25 00:00:00</p>
		parser.reset();
		filter = new AndFilter(new TagNameFilter("p"),new HasAttributeFilter("style","padding-left:10px;")) ;
		nodeList = parser.parse(filter);
		Node coNode  =  nodeList.elementAt(0);
		Node timeNode = nodeList.elementAt(1);
		strs[1] = coNode.toPlainTextString().replace("唱片公司：", "");
		strs[2] = timeNode.toPlainTextString().replace("发行日期：", "");
		return strs;
	}

	private String parseAlbumIntro(Parser parser) throws ParserException {
		parser.reset();
		//<p style="padding:0 10px; line-height:22px;">
		NodeFilter filter = new AndFilter(new TagNameFilter("p"),
				new HasAttributeFilter("style", "padding:0 10px; line-height:22px;"));
		NodeList nodeList = parser.parse(filter);
		if (nodeList.size() <= 0) {
			return null;
		}
		Node node =  nodeList.elementAt(0);
		return node.toPlainTextString();
	}

	public List<Song> getSongs(Parser parser) throws ParserException {
		List<Song> songs = new ArrayList<Song>(10);
		parser.reset();
	//<ul class="top100list clearfix"   // style="width:663px;"
		NodeFilter filter = new AndFilter(new TagNameFilter("ul"),new HasAttributeFilter("style","width:663px"));
		NodeList nodeList = parser.parse(filter);
		for (int i = 0; i < nodeList.size();i++) {
			Song song = new Song();
			Tag tag = (Tag) nodeList.elementAt(i);
			NodeList liList = new NodeList();
			NodeFilter lifilter = new TagNameFilter("li");
			tag.collectInto(liList, lifilter);
			//解析一首歌的ul之中的li元素
			String songNetid=null;
			String style = null;
			String songName=null;
			String language =null;
			String idnum=null;
			String singerFromId = null;
			String lrcid =null;
			for (int j = 0; j < liList.size();j++) {
				Node li = liList.elementAt(j);
				String liHtml = li.toHtml();
				if (liHtml.indexOf("class=\"No2\"")!=-1) {
					// href="http://www.top100.cn/song/?song=jwadgctugr4drcbo8r"
					songNetid=RegexUtils.getMatcheGroup(".*song=([^\"]*)\".*", liHtml);
					//title="卡农">卡农</a></li>
					songName = RegexUtils.getMatcheGroup(".*title=\"([^\"]*)\".*", liHtml);
				}else if (liHtml.indexOf("class=\"No4\"")!=-1) {
					//<li class="No4" style="overflow:hidden;">中国台湾</li>
		        //    <li class="No4" style="overflow:hidden;">华语流行音乐【Chinese Pop Music】&nbsp;</li>
					if (language==null) {
						language =li.toPlainTextString();
					}else{
						style = li.toPlainTextString().replace("&nbsp;", "");
					}
				}else if (liHtml.indexOf("class=\"No6\"")!=-1) {
					NodeList list=li.getChildren();
					idnum = ((InputTag) list.elementAt(0)).getAttribute("value");
					lrcid = ((InputTag) list.elementAt(4)).getAttribute("value");
				}else if (liHtml.indexOf("class=\"No3\"")!=-1) {
					//<a href='/artist/info-aga4uy.shtml' title='张惠妹' target='_blank'>张惠妹</a>&nbsp;
					singerFromId = RegexUtils.getMatcheGroup(".*info-([^\\.]*)\\.shtml.*", liHtml);
				}
			}
			song.setNetId(songNetid);
			//song.setName(songName);//--------------------------------
			song.setStyle(style);
			song.setLanguage(language);
			song.setType(idnum);
			//song.setLrcid(lrcid);//---------------------------------
			song.setFromUrl(singerFromId);
			songs.add(song);
			
		}
		return songs;
	}

	private String parseAlbumName(Parser parser) throws ParserException {
		parser.reset();
		// <div class="special_tit">阿密特 首次世界巡回演唱会 CD1</div>                       special_tit
		NodeFilter filter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class","special_tit")); 
		NodeList nodeList = parser.parse(filter);
		Node nameNode = nodeList.elementAt(0);
		return nameNode.toPlainTextString();
	}
	
	
}
